<template>
  <div>
    <header class="game_modal_header">分站赛</header>
    <div v-show="timeLineList.length">
      <div class="schedule_content">
        <div class="timeLine_wrap">
          <div class="timeLine_content">
            <div class="timeLine_main">
              <ul ref="timeLinePointList" class="timeLine_point_list" :style="{width: timeLineInfo.totalWidth + 'px', left: timeLineInfo.left + 'px'}">
                <li
                  v-for="(item, index) in timeLineList"
                  :key="index"
                  :class="{active: timeLineInfo.activeTimeLine === index}"
                  class="timeLine_point_item"
                  @click="changeTimeLineItem(index)"
                >
                  <div class="timeLine_point_content" />
                  <div class="timeLine_point_date">{{ item.startTime }}</div>
                </li>
              </ul>
            </div>
          </div>
          <div class="timeLine_line" />
          <div class="timeLine_left" @click="clickTimeLineToMoveLeft" />
          <div class="timeLine_right" @click="clickTimeLineToMoveRight" />
        </div>
      </div>
      <div class="schedule_content">
        <div class="sub_game gl_clear">
          <div class="sub_game_img_wrap gl_fl">
            <img
              v-for="(item, index) in substationList"
              :key="index"
              :class="index === activeIndex ? 'active' : ''"
              class="sub_game_img"
              :src="getStaticFileUrl(item.backgroundImage)"
              @click="clickSubstationBgImage"
            >
          </div>
          <ul class="sub_game_list gl_fl">
            <li
              v-for="(item, index) in substationList"
              :key="index"
              :class="index === activeIndex ? 'active' : ''"
              class="sub_game_item gl_clear"
              @mouseenter="changeSubGameIndex(index)"
              @mouseleave="changeSubGameIndex(index)"
            >
              <div class="game_info_wrap gl_clear">
                <div class="game_logo gl_fl">
                  <img class="game_logo_img" :src="getStaticFileUrl(item.logoImage)" @click="jumpToSubstationHomePage(item)">
                </div>
                <div class="game_info">
                  <div class="game_title gl_ellipsis" :title="(item.parent ? item.parent.name + '-' : '') + item.name" @click="jumpToSubstationHomePage(item)">
                    {{ item.parent ? item.parent.name + '-' : '' }}{{ item.name }}
                  </div>
                  <div class="game_time">比赛时间：{{ item.startTime ? item.startTime.slice(0, 10) : '' }} 至 {{ item.endTime ? item.endTime.slice(0, 10) : '' }}</div>
                  <div class="game_time">报名时间：{{ item.entryStartTime ? item.entryStartTime.slice(0, 10) : '' }} 至 {{ item.entryEndTime ? item.entryEndTime.slice(0, 10) : '' }}</div>
                </div>
                <div v-if="item.status.code !== 'EntryStarted'" class="entry_btn">{{ item.status.name }}</div>
                <div v-else class="entry_btn pointer enabled" @click="jumpToSubstationHomePage(item)">{{ item.status.name }}</div>
              </div>
            </li>
          </ul>
        </div>
        <div class="more_wrap gl_clear">
          <span class="more_btn pointer gl_fr" @click="jumpToSubstation">更多</span>
        </div>
      </div>
    </div>
    <div v-show="!timeLineList.length" class="no_substation">
      暂无分站赛数据，快去申办比赛吧！
    </div>
  </div>
</template>

<script>
import {
  api_GET_EventsManagementCompetitionChildren2 // 获取分站赛列表（不需要权限）
} from '@/extend/api/gameswaggerApi/app';

import {
  Api_GET_EventsManagementCompetitionChildren2QO // 获取分站赛列表（不需要权限）
} from '@/lib/form/game/swaggerForm';

export default {
  props: {
    gameInfo: {
      type: Object,
      default () {
        return {};
      }
    }
  },
  data () {
    return {
      activeIndex: 0,
      timeLineList: [],
      timeLineInfo: { // 时间线相关数据
        activeTimeLine: 0, // 当前选中的时间节点
        wrapWidth: 980,
        totalWidth: 0, // 时间节点容器总宽度
        left: 0,
        itemWidth: 130, // 每个时间节点占用宽度
        itemLen: 0, // 数据长度，共多少个时间点
        moveNum: 3 // 移动时的数量
      },
      qo: new Api_GET_EventsManagementCompetitionChildren2QO()
    };
  },
  computed: {
    substationList () {
      return this.timeLineList[this.timeLineInfo.activeTimeLine] ? this.timeLineList[this.timeLineInfo.activeTimeLine].children.slice(0, 3) : [];
    }
  },
  watch: {
    gameInfo: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val.id) {
          this.getPageList();
        }
      }
    }
  },
  methods: {
    getPageList() {
      const _qo = JSON.parse(JSON.stringify(this.qo));
      delete _qo.Page;
      delete _qo.SkipCount;
      delete _qo.MaxResultCount;
      _qo.ParentId = this.gameInfo.id;
      _qo.IsPublished = true;
      _qo.HasParent = true;
      // _qo.IsFinal = true;
      _qo.HasFinalQualification = true;
      _qo.IncludeStatus = true;
      // _qo.IncludeType = true;
      // _qo.IncludeApproveStatus = true;
      // _qo.IncludeLevel = true;
      // _qo.IncludeSetting = true;
      // _qo.IncludeReportSetting = true;
      // _qo.IncludeEntryFields = true;
      _qo.IncludeParent = true;
      delete _qo.IsFinal; // 不需要传isFinal, isfinal=true 则只查决赛;isfinal=false 则只查非决赛;不传查所有
      this.apiCompetitionChildren(_qo);
    },
    // 获取分站赛列表（不需要权限）
    apiCompetitionChildren(qo) {
      api_GET_EventsManagementCompetitionChildren2(qo)
        .then(
          res => {
            this.timeLineList = this.formatTimeLineData(res.items);
            this.timeLineInfo.activeTimeLine = this.chooseActiveTimeLineByCurrentDate(this.timeLineList);
            this.initTimeLine();
            this.timeLineInfo.left = this.setLeftBychooseActiveTimeLine();
          }
        )
        .catch(
          error => {
            console.log(error);
          }
        );
    },
    setLeftBychooseActiveTimeLine () {
      const activeTimeLine = this.timeLineInfo.activeTimeLine;
      const maxNum = 7; // 一屏显示8个，从0开始
      if (activeTimeLine > maxNum) {
        return -((activeTimeLine - maxNum) * this.timeLineInfo.itemWidth);
      }
      return 0;
    },
    changeTimeLineItem (index) {
      this.timeLineInfo.activeTimeLine = index;
      this.activeIndex = 0;
    },
    clickSubstationBgImage () {
      const _item = this.substationList[this.activeIndex];
      this.jumpToSubstationHomePage(_item);
    },
    jumpToSubstationHomePage (item) {
      const _origin = window.location.origin;
      var a = document.createElement('a');
      var event = new MouseEvent('click');
      a.href = `${_origin}/game.html#/home/${item.route}/info`;
      a.target = '_blank';
      a.dispatchEvent(event);
    },
    // 根据当前日期选择时间线的选中日期
    chooseActiveTimeLineByCurrentDate (list) {
      const curDate = new Date();
      const curYear = curDate.getFullYear();
      const curMonth = curDate.getMonth() < 9 ? '0' + curDate.getMonth() + 1 : curDate.getMonth() + 1;
      const curDateStr = curYear + '-' + curMonth;
      let i;
      for (i = 0; i < list.length; i++) {
        const _startTime = list[i].startTime;
        if (curDateStr <= _startTime) return i;
      }
      return --i;
    },
    formatTimeLineData (list) {
      const _timeLineData = {};
      for (let i = 0; i < list.length; i++) {
        const item = list[i];
        const _startTime = item.startTime ? item.startTime.slice(0, 7) : '';
        if (_startTime in _timeLineData) {
          _timeLineData[_startTime].children.push(item);
        } else {
          _timeLineData[_startTime] = {
            startTime: _startTime,
            children: [item]
          };
        }
      }
      const _timeLineList = Object.values(_timeLineData);
      _timeLineList.sort((a, b) => {
        const _aTime = a.startTime;
        const _bTime = b.startTime;
        if (_aTime > _bTime) { return 1; }
        if (_aTime < _bTime) { return -1; }
        return 0;
      });
      return _timeLineList;
    },
    // 切换赛事顺序
    changeSubGameIndex (index) {
      this.activeIndex = index;
    },
    initTimeLine () {
      // 初始化时间线，计算宽度等操作
      this.timeLineInfo.itemLen = this.timeLineList.length;
      this.timeLineInfo.totalWidth = this.timeLineList.length * this.timeLineInfo.itemWidth;
    },
    clickTimeLineToMoveLeft () {
      const _left = this.$refs.timeLinePointList.offsetLeft;
      const _computLeft = _left + (this.timeLineInfo.itemWidth * this.timeLineInfo.moveNum);
      if (_computLeft >= 0) {
        this.timeLineInfo.left = 0;
      } else {
        this.timeLineInfo.left = _computLeft;
      }
    },
    clickTimeLineToMoveRight () {
      const _left = this.$refs.timeLinePointList.offsetLeft;
      const _computLeft = Math.abs(_left) + (this.timeLineInfo.itemWidth * this.timeLineInfo.moveNum);
      const _maxLeft = this.timeLineInfo.totalWidth - this.timeLineInfo.wrapWidth;
      if (_maxLeft <= 0) return;
      if (_computLeft <= _maxLeft) {
        this.timeLineInfo.left = -1 * _computLeft;
      } else {
        this.timeLineInfo.left = -1 * _maxLeft;
      }
    },
    getStaticFileUrl(relativeUrl) {
      if (!relativeUrl) return '';
      return WEB_CONFIG.VUE_APP_STATIC_FILE_RUL + relativeUrl;
    },
    // 跳转至分站赛
    jumpToSubstation () {
      this.$router.push({
        name: 'Substation'
      });
    }
  }
};
</script>

<style lang="scss" scoped>
  .timeLine_wrap {
    position: relative;
    width: 100%;
    height: 80px;
  }
  .timeLine_line {
    position: absolute;
    left: 0;
    top: 50%;
    width: 100%;
    height: 1px;
    background-color: #32456C;
  }
  .timeLine_left {
    position: absolute;
    width: 11px;
    height: 11px;
    left: 0;
    top: 50%;
    margin-top: -5px;
    background-color: #32456C;
    border-radius: 50%;
    z-index: 3;
    cursor: pointer;
  }
  .timeLine_right {
    position: absolute;
    width: 11px;
    height: 11px;
    right: 0;
    top: 50%;
    margin-top: -5px;
    background-color: #32456C;
    border-radius: 50%;
    z-index: 3;
    cursor: pointer;
  }
  .timeLine_content {
    position: relative;
    height: 100%;
    padding: 0 70px;
    z-index: 2;
  }
  .timeLine_main {
    height: 100%;
    overflow: hidden;
    position: relative;
  }
  .timeLine_point_list {
    position: relative;
    padding: 0 20px;
    left: 0;
    top: 0;
    white-space: nowrap;
    height: 100%;
    font-size: 0;
    transition: 0.3s;
  }
  .timeLine_point_item {
    display: inline-block;
    position: relative;
    width: 30px;
    height: 30px;
    margin-top: 25px;
    margin-right: 100px;
    vertical-align: top;
    font-size: 16px;
    text-align: center;
    color: #FFF;
    border-radius: 50%;
  }
  .timeLine_point_content {
    width: 100%;
    height: 100%;
    transition: 0.3s;
    transform-origin: center;
    cursor: pointer;
    background-color: #32456C;
    background-image: url('../../../../../assets/images/league/taekwondo.png');
    background-repeat: no-repeat;
    background-position: center center;
    transform: scale(0.8);
    border-radius: 50%;
  }
  .timeLine_point_item:last-child {
    margin-right: 0;
  }
  .active .timeLine_point_content {
    transform: scale(1);
    background-color: #E02020;
  }
  .timeLine_point_date {
    position: absolute;
    left: -50%;
    top: -25px;
    color: #000;
  }
  .active .timeLine_point_date {
    position: absolute;
    left: -50%;
    top: -25px;
    margin-left: 0;
    color: #000;
  }

  .sub_game_img_wrap {
    position: relative;
    width: 582px;
    height: 312px;
    border-radius: 8px;
    box-shadow: 0px 10px 30px 0px rgba(0,0,0,0.10);
    overflow: hidden;
  }
  .sub_game_img {
    width: 100%;
    opacity: 0;
    position: absolute;
    transition: 0.3s;
    cursor: pointer;
  }
  .sub_game_img.active {
    opacity: 1;
  }

  .sub_game_list {
    margin-left: 20px;
  }
  .sub_game_item {
    position: relative;
    width: 518px;
    height: 90px;
    margin-bottom: 21px;
    border-radius: 8px;
    box-shadow: 0px 10px 20px 0px rgba(0,0,0,0.10);
    background-image: url('../../../../../assets/images/league/bg_home.png');
    background-position-x: right;
    background-repeat: no-repeat;
  }
  .sub_game_item.active::after {
    display: block;
    position: absolute;
    left: -8px;
    top: 36px;
    content: "";
    border: 8px solid #DC1D1D;
    border-right-color: transparent;
    border-bottom-color: transparent;
    border-radius: 4px;
    transform: rotate(-45deg);
  }
  .sub_game_item:last-child {
    margin-bottom: 0;
  }
    .game_info_wrap {
    height: 90px;
    position: relative;
  }
  .game_logo {
    width: 95px;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .game_logo_img {
    width: 52px;
    height: 52px;
    border-radius: 50%;
    cursor: pointer;
  }
  .game_info {
    padding-left: 95px;
    height: 100%;
  }
  .game_title {
    padding-top: 16px;
    margin-bottom: 6px;
    line-height: 22px;
    font-size: 16px;
    font-weight: bold;
    color: #353434;
    cursor: pointer;
  }
  .game_time {
    margin-bottom: 4px;
    font-size: 12px;
    line-height: 17px;
    color: #353434;
  }
  .entry_btn {
    position: absolute;
    padding: 0 12px;
    line-height: 28px;
    font-size: 14px;
    background-color: #c8c8c8;
    color: #FFF;
    right: 20px;
    bottom: 10px;
    border-radius: 8px;
  }
  .entry_btn.enabled {
    background-color: #DC1D1D;
  }
  .pointer {
    cursor: pointer;
  }

  .more_wrap {
    padding: 20px;
  }
  .more_btn {
    color: #D01528;
    font-size: 12px;
  }

  .no_substation {
    min-height: 447px;
    padding: 40px 0 20px;
    font-size: 14px;
    text-align: center;
    color: #909399;
  }
</style>
